package cn.com.generaldata.os.service.indicator_evaluation.coefficient_of_variation;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.Validate;

import cn.com.generaldata.jsme_indicator_system.entity.IndicatorEvaluation;
import cn.com.generaldata.os.service.indicator_constant.ProvinceIndicatorConstant;
import cn.com.generaldata.os.service.indicator_evaluation.IndicatorEvaluationCalculateService;
import cn.com.generaldata.os.util.BeanMapper;
import cn.com.generaldata.os.vo.IndicatorAccountVO;

/**
 * GOP的Moran's I评估指标计算类.
 */
public class GOPMoransICalculateService extends IndicatorEvaluationCalculateService {
	private String[] cityAreas = ProvinceIndicatorConstant.CITYS;
	private String GOPArea = ProvinceIndicatorConstant.GOP_INDICATOR_NAME;
	private Integer[][] W = ProvinceIndicatorConstant.MORANW;

	@Override
	protected Double calculate(IndicatorEvaluation indicator, IndicatorAccountVO indicatorAccountVO) {
		IndicatorAccountVO iav = BeanMapper.map(indicatorAccountVO, IndicatorAccountVO.class);
		Double xSum = 0d;
		Map cityLEMap = new HashMap();
		for (String city : cityAreas) {
			iav.setAreaId(city);
			// 城市GOP
			Double gopCity = getInputOrAccountingIndicatorValue(iav, indicatorAccountVO.getYear(), GOPArea);
			Validate.isTrue(gopCity != null);
			cityLEMap.put(city, gopCity);
			xSum += gopCity;
		}
		Double xAverage = xSum / 3;
		Double iSum = 0d;
		Double wSum = 0d;
		Double sum = 0d;
		for (int i = 0; i < W.length; i++)
		{
			Double xi = (Double) cityLEMap.get(cityAreas[i]);
			for (int j = 0; j < W[i].length; j++)
			{
				Double xj = (Double) cityLEMap.get(cityAreas[j]);
				sum += W[i][j] * (xi - xAverage) * (xj - xAverage);
				wSum += W[i][j];
			}
			iSum += Math.pow((xi - xAverage), 2);
		}

		return -((3 / wSum) * (sum / iSum));
	}
}
